package com.bihua.blog.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bihua.blog.domain.CmsBlog;
import com.bihua.blog.domain.CmsBlogTag;
import com.bihua.blog.domain.CmsBlogType;
import com.bihua.blog.domain.bo.CmsBlogBo;
import com.bihua.blog.domain.bo.CmsBlogTagBo;
import com.bihua.blog.domain.bo.CmsBlogTypeBo;
import com.bihua.blog.domain.bo.CmsTagBo;
import com.bihua.blog.domain.bo.CmsTypeBo;
import com.bihua.blog.domain.vo.CmsBlogAllTagAndAllTypeVo;
import com.bihua.blog.domain.vo.CmsBlogTagVo;
import com.bihua.blog.domain.vo.CmsBlogTypeVo;
import com.bihua.blog.domain.vo.CmsBlogVo;
import com.bihua.blog.domain.vo.CmsTagVo;
import com.bihua.blog.domain.vo.CmsTypeVo;
import com.bihua.blog.mapper.CmsBlogMapper;
import com.bihua.blog.service.ICmsBlogService;
import com.bihua.blog.service.ICmsBlogTagService;
import com.bihua.blog.service.ICmsBlogTypeService;
import com.bihua.blog.service.ICmsTagService;
import com.bihua.blog.service.ICmsTypeService;
import com.bihua.common.core.domain.PageQuery;
import com.bihua.common.core.page.TableDataInfo;
import com.bihua.common.utils.BeanCopyUtils;
import com.bihua.common.utils.StringUtils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;

/**
 * 博客信息Service业务层处理
 *
 * @author bihua
 * @date 2023-05-30
 */
@RequiredArgsConstructor
@Service
public class CmsBlogServiceImpl implements ICmsBlogService {

    private final CmsBlogMapper baseMapper;

    private final ICmsBlogTagService iCmsBlogTagService;
    private final ICmsTagService iCmsTagService;
    private final ICmsBlogTypeService iCmsBlogTypeService;
    private final ICmsTypeService iCmsTypeService;
    /**
     * 查询博客信息
     */
    @Override
    public CmsBlogVo queryById(Long id){
        CmsBlogVo vo = baseMapper.selectVoById(id);
        Long blogId = vo.getId();
        //查询标签列表
        CmsBlogTagBo cmsBlogTagBo = new CmsBlogTagBo();
        cmsBlogTagBo.setBlogId(blogId);
        List<CmsBlogTagVo> blogTagList = iCmsBlogTagService.queryList(cmsBlogTagBo);
        if (CollectionUtil.isNotEmpty(blogTagList)){
            List<Long> tagIds = new ArrayList<>();
            blogTagList.forEach((CmsBlogTagVo cmsBlogTagVo)->{
                tagIds.add(cmsBlogTagVo.getTagId());
            });
            vo.setTagIds(tagIds.toArray(new Long[0]));
        }
        //查询分类列表
        CmsBlogTypeBo cmsBlogTypeBo = new CmsBlogTypeBo();
        cmsBlogTypeBo.setBlogId(blogId);
        List<CmsBlogTypeVo> blogTypeList = iCmsBlogTypeService.queryList(cmsBlogTypeBo);
        if (CollectionUtil.isNotEmpty(blogTypeList)){
            List<Long> typeIds = new ArrayList<>();
            blogTypeList.forEach((CmsBlogTypeVo cmsBlogTypeVo)->{
                typeIds.add(cmsBlogTypeVo.getTypeId());
            });
            vo.setTypeIds(typeIds.toArray(new Long[0]));
        }
        return vo;
    }

    /**
     * 查询博客信息列表
     */
    @Override
    public TableDataInfo<CmsBlogVo> queryPageList(CmsBlogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CmsBlog> lqw = buildQueryWrapper(bo);
        Page<CmsBlogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (result==null || result.getRecords() ==null || result.getRecords().size()<0){
            return TableDataInfo.build(result);
        }
        for (CmsBlogVo vo : result.getRecords()) {
            appendTypesAndTags(vo);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询博客信息列表
     */
    @Override
    public List<CmsBlogVo> queryList(CmsBlogBo bo) {
        LambdaQueryWrapper<CmsBlog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CmsBlog> buildQueryWrapper(CmsBlogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CmsBlog> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), CmsBlog::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), CmsBlog::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getTop()), CmsBlog::getTop, bo.getTop());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), CmsBlog::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增博客信息
     */
    @Override
    public Long insertByBo(CmsBlogBo bo) {
        CmsBlog add = BeanUtil.toBean(bo, CmsBlog.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            //新增文章标签
            Long[] tagIds = bo.getTagIds();
            if (tagIds!=null&&tagIds.length>0){
                List<CmsBlogTag> blogTagList = new ArrayList<>();
                for (Long tagId : tagIds) {
                    CmsBlogTag cmsBlogTag = new CmsBlogTag();
                    cmsBlogTag.setBlogId(bo.getId());
                    cmsBlogTag.setTagId(tagId);
                    blogTagList.add(cmsBlogTag);
                }
                iCmsBlogTagService.insertBatch(blogTagList);
            }
            //新增文章分类
            Long[] typeIds = bo.getTypeIds();
            if (typeIds!=null&&typeIds.length>0){
                List<CmsBlogType> blogTypeList = new ArrayList<>();
                for (Long typeId : typeIds) {
                    CmsBlogType cmsBlogType = new CmsBlogType();
                    cmsBlogType.setBlogId(bo.getId());
                    cmsBlogType.setTypeId(typeId);
                    blogTypeList.add(cmsBlogType);
                }
                iCmsBlogTypeService.insertBatch(blogTypeList);
            }
            return add.getId();
        }
        return null;
    }

    /**
     * 修改博客信息
     */
    @Override
    public Boolean updateByBo(CmsBlogBo bo) {
        CmsBlog update = BeanUtil.toBean(bo, CmsBlog.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CmsBlog entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除博客信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public CmsBlogAllTagAndAllTypeVo getAllTagAndAllType() {
        List<CmsTagVo> cmsTagList = iCmsTagService.queryList(new CmsTagBo());
        List<CmsTypeVo> cmsTypeList = iCmsTypeService.queryList(new CmsTypeBo());
        return new CmsBlogAllTagAndAllTypeVo(cmsTagList, cmsTypeList);
    }

    @Override
    public TableDataInfo<CmsBlogVo> selectCmsBlogListByTypeId(Long typeId, PageQuery pageQuery) {
        Page<CmsBlog> pageData = baseMapper.selectCmsBlogListByTypeId(pageQuery.build(), typeId);
        IPage<CmsBlogVo> result = new Page<>(pageData.getCurrent(), pageData.getSize(), pageData.getTotal());
        if (CollUtil.isEmpty(pageData.getRecords())) {
            return TableDataInfo.build(result);
        }
        result.setRecords(BeanCopyUtils.copyList(pageData.getRecords(), CmsBlogVo.class));
        for (CmsBlogVo vo : result.getRecords()) {
            appendTypesAndTags(vo);
        }
        return TableDataInfo.build(result);
    }

    private void appendTypesAndTags(CmsBlogVo vo) {
        Long blogId = vo.getId();
        //查询标签列表
        CmsBlogTagBo cmsBlogTagBo = new CmsBlogTagBo();
        cmsBlogTagBo.setBlogId(blogId);
        List<CmsBlogTagVo> blogTagList = iCmsBlogTagService.queryList(cmsBlogTagBo);
        List<Long> tagIds = new ArrayList<>();
        blogTagList.forEach((CmsBlogTagVo cmsBlogTagVo) -> {
            tagIds.add(cmsBlogTagVo.getTagId());
        });
        List<CmsTagVo> cmsTagList = iCmsTagService.queryListByIds(tagIds);
        vo.setTags(cmsTagList);
        //查询分类列表
        CmsBlogTypeBo cmsBlogTypeBo = new CmsBlogTypeBo();
        cmsBlogTypeBo.setBlogId(blogId);
        List<CmsBlogTypeVo> blogTypeList = iCmsBlogTypeService.queryList(cmsBlogTypeBo);
        List<Long> typeIds = new ArrayList<>();
        blogTypeList.forEach((CmsBlogTypeVo cmsBlogTypeVo) -> {
            typeIds.add(cmsBlogTypeVo.getTypeId());
        });
        List<CmsTypeVo> cmsTypeList = iCmsTypeService.queryListByIds(typeIds);
        vo.setTypes(cmsTypeList);
    }
}
